import {defineStore} from 'pinia'
import axios from "axios";
import { Qiniu_uploadFile, useQiniuStorage} from "./qiniu.ts";
import {Constant, MyUrl, Song} from "../hook/Constant.ts";

import "vue-router/dist/vue-router";
import router from "./router.ts";
import {hook_getFavoriteByUserId} from "../hook/UserHook.ts";
import {useToast} from "vue-toastification";


export let useSongStore = defineStore('song', {
    state: () => ({
        song: new Song(),
        status: Constant.DEFAULT,
    }),
    actions: {
        upload: async function () {
            try {
                //1.先上传到qiniu
                this.song.url = Qiniu_uploadFile(this.song.url, this.song.url.name, Constant.FOLDER_MUSIC);
                while (true) {
                    if (useQiniuStorage().isUpdateStatus == Constant.SUCCESS) {
                        await new Promise(resolve => {
                            setTimeout(resolve, 3000)
                        })
                        break;
                    } else if (useQiniuStorage().isUpdateStatus == Constant.ERROR) {
                        throw new Error("上传失败");
                    } else if (useQiniuStorage().isUpdateStatus == Constant.LOADING) {
                        //阻塞1秒再次判断
                        useToast().info("上传中。。请不要关闭界面 "+ String(Math.floor(useQiniuStorage().nextInfo.total.percent))+"%")
                    }
                    //阻塞1秒再次判断
                    await new Promise(resolve => {
                        setTimeout(resolve, 1000)
                    })
                }

                //2.把数据上传到数据库
                axios.post(MyUrl.SONG_addSong,
                    JSON.stringify(this.song), {
                        headers: {
                            'Content-Type': "application/json"
                        }
                    }
                ).then(res => {
                    console.log(res.data)
                    //接收到的响应信息
                    if (res.data.flag) {
                        this.status = Constant.SUCCESS
                        router.push('/user')
                        useToast().success("音乐上传成功")
                    } else {
                        useToast().error("音乐上传失败:" + res.data.message)
                        console.error(res.data.message)
                    }
                })
            } catch (e) {
                useToast().error("音乐上传失败:" + e)
                //取消文件上传
                useQiniuStorage().isUpdateStatus = Constant.ERROR
            }
        },
    }
})


//store配置
export const useAuthStore = defineStore('auth', {
    state: () => ({
        //创建状态管理属性
        isAuthenticated: sessionStorage.getItem('isAuthenticated'),
        isEditPassword: false,
        editEmail: null,
        user: {
            id: null,
            username: null,
            password: null,
            gender: null,
            email: null,
            phone: null,
            remark: null,
            avatar: null,
            favorite: null,
        },
    }),
    actions: {
        //定义登录相关的函数
        login(user) {
            //向后端发送请求验证密码通过返回登录信息
            axios.get(MyUrl.USER_login, {
                params:{
                    email: user.email,
                    password: user.password,
                }
            }).then(async (res) => {
                console.log(res)
                //接收到的响应信息
                if (res.data.flag) {
                    //更改用户状态
                    console.log("登录成功")
                    this.user = res.data.data
                    this.isAuthenticated = true
                    this.favorite = await hook_getFavoriteByUserId(this.user.id)

                    //存储用户登录信息到本地
                    sessionStorage.setItem('isAuthenticated', 'true');
                    sessionStorage.setItem("user", JSON.stringify(this.user));
                    sessionStorage.setItem("favorite", JSON.stringify(this.favorite));


                    //跳转到用户界面
                    await router.push('/user')

                    //等待跳转到页面后刷新页面
                    location.reload()
                    useToast().success("登录成功")
                } else {
                    console.log("登录失败")
                    useToast().error("登录失败")
                }
            })
        },
        logout() {
            //登出是删除session
            sessionStorage.removeItem("isAuthenticated")
            sessionStorage.removeItem("user")
            //跳转到到登录界面
        },
        register_step1(user) {
            //先由store保管起来
            this.user.username = user.username
            this.user.password = user.password
            this.user.gender = user.gender
            this.user.email = user.email

            //跳转到下一步
            router.push('/improveInfo')
        },
        register_step2(user) {
            //由store保管起来
            this.user.avatar = user.avatar
            this.user.remark = user.remark
            this.user.phone = user.phone


            if (this.user.avatar != null) {
                //到这里基本上已经提取到所需要的用户信息了
                //1.上传头像,里面会自动替换avatar为图片链接,指定文件夹
                this.user.avatar = Qiniu_uploadFile(this.user.avatar,this.user.avatar.name,Constant.FOLDER_IMG)
            }

            //2.将user数据上传到数据库
            axios.post(MyUrl.USER_register, {
                username: this.user.username,
                password: this.user.password,
                gender: this.user.gender,
                email: this.user.email,
                phone: this.user.phone,
                remark: this.user.remark,
                avatar: this.user.avatar,
            }).then((res) => {
                //3.接收返回消息后，更新user信息
                this.user=res.data.data

                //4.跳转到/login,让用户自己登录
                router.push('/login')
            })
        },
    }
})


